package com.sky.controller.admin;

import com.sky.aspect.QueryPerformanceAspect;
import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 查询性能监控控制器
 * 用于查看数据库查询性能统计信息
 */
@RestController
@RequestMapping("/admin/query-performance")
@Api(tags = "查询性能监控相关接口")
@Slf4j
public class QueryPerformanceController {

    @Autowired
    private QueryPerformanceAspect queryPerformanceAspect;

    /**
     * 获取查询性能统计信息
     */
    @GetMapping("/stats")
    @ApiOperation("获取查询性能统计信息")
    public Result<Map<String, Object>> getQueryStats() {
        log.info("获取查询性能统计信息");
        
        Map<String, Object> result = new HashMap<>();
        Map<String, QueryPerformanceAspect.QueryStats> stats = queryPerformanceAspect.getQueryStats();
        
        // 计算总体统计信息
        long totalQueries = 0;
        long totalSuccess = 0;
        long totalTime = 0;
        long maxTime = 0;
        long minTime = Long.MAX_VALUE;
        
        for (QueryPerformanceAspect.QueryStats stat : stats.values()) {
            totalQueries += stat.getTotalCount();
            totalSuccess += stat.getSuccessCount();
            totalTime += stat.getTotalTime();
            maxTime = Math.max(maxTime, stat.getMaxTime());
            if (stat.getMinTime() > 0) {
                minTime = Math.min(minTime, stat.getMinTime());
            }
        }
        
        Map<String, Object> summary = new HashMap<>();
        summary.put("totalQueries", totalQueries);
        summary.put("totalSuccess", totalSuccess);
        summary.put("totalTime", totalTime);
        summary.put("maxTime", maxTime == 0 ? 0 : maxTime);
        summary.put("minTime", minTime == Long.MAX_VALUE ? 0 : minTime);
        summary.put("avgTime", totalQueries > 0 ? (double) totalTime / totalQueries : 0);
        summary.put("successRate", totalQueries > 0 ? (double) totalSuccess / totalQueries : 0);
        
        result.put("summary", summary);
        result.put("details", stats);
        
        return Result.success(result);
    }

    /**
     * 重置查询性能统计信息
     */
    @PostMapping("/reset")
    @ApiOperation("重置查询性能统计信息")
    public Result<String> resetQueryStats() {
        log.info("重置查询性能统计信息");
        queryPerformanceAspect.resetStats();
        return Result.success("统计信息已重置");
    }

    /**
     * 获取慢查询列表
     */
    @GetMapping("/slow-queries")
    @ApiOperation("获取慢查询列表")
    public Result<Map<String, Object>> getSlowQueries() {
        log.info("获取慢查询列表");
        
        Map<String, Object> result = new HashMap<>();
        Map<String, QueryPerformanceAspect.QueryStats> stats = queryPerformanceAspect.getQueryStats();
        
        // 筛选慢查询（平均执行时间超过500ms）
        Map<String, QueryPerformanceAspect.QueryStats> slowQueries = new HashMap<>();
        for (Map.Entry<String, QueryPerformanceAspect.QueryStats> entry : stats.entrySet()) {
            if (entry.getValue().getAvgTime() > 500) {
                slowQueries.put(entry.getKey(), entry.getValue());
            }
        }
        
        result.put("slowQueries", slowQueries);
        result.put("count", slowQueries.size());
        
        return Result.success(result);
    }

    /**
     * 获取查询性能报告
     */
    @GetMapping("/report")
    @ApiOperation("获取查询性能报告")
    public Result<Map<String, Object>> getPerformanceReport() {
        log.info("获取查询性能报告");
        
        Map<String, Object> result = new HashMap<>();
        Map<String, QueryPerformanceAspect.QueryStats> stats = queryPerformanceAspect.getQueryStats();
        
        // 性能评级
        Map<String, String> performanceGrades = new HashMap<>();
        for (Map.Entry<String, QueryPerformanceAspect.QueryStats> entry : stats.entrySet()) {
            double avgTime = entry.getValue().getAvgTime();
            String grade;
            if (avgTime < 100) {
                grade = "优秀";
            } else if (avgTime < 500) {
                grade = "良好";
            } else if (avgTime < 1000) {
                grade = "一般";
            } else {
                grade = "需要优化";
            }
            performanceGrades.put(entry.getKey(), grade);
        }
        
        result.put("performanceGrades", performanceGrades);
        result.put("totalMethods", stats.size());
        
        // 计算各等级的数量
        long excellent = performanceGrades.values().stream().filter("优秀"::equals).count();
        long good = performanceGrades.values().stream().filter("良好"::equals).count();
        long normal = performanceGrades.values().stream().filter("一般"::equals).count();
        long needOptimization = performanceGrades.values().stream().filter("需要优化"::equals).count();
        
        Map<String, Long> gradeCounts = new HashMap<>();
        gradeCounts.put("优秀", excellent);
        gradeCounts.put("良好", good);
        gradeCounts.put("一般", normal);
        gradeCounts.put("需要优化", needOptimization);
        
        result.put("gradeCounts", gradeCounts);
        
        return Result.success(result);
    }
}











